//
//  ResetPassView2.m
//  specialine
//
//  Created by 往返网络 on 17/2/10.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ResetPassView2.h"

#define RETURN_BTN 1000  //上级界面

#define NEXT_View  2000 //下一页


@interface ResetPassView2 ()<UITextFieldDelegate>


//开辟多线程定时器，在后台执行，比NSTimer更自然

@property (nonatomic,strong) dispatch_source_t timer;

@end

@implementation ResetPassView2
{
    
    UITextField * yanzhengtf;
    
    UIButton  * nextbtn; //下一步
    
    UIButton * resetyanzhengbtn; //重新发送验证码
    
    
}


- (instancetype)initWithFrame:(CGRect)frame andPhonestring:(NSString *)phonestring{


    if (self = [super initWithFrame: frame]) {
        
        
        [self createUIwithPhonestring:phonestring];
        
    }
    


    return self;

}

- (void)loadTimer{
    
    
    __block NSInteger time = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [resetyanzhengbtn setTitle:@"重新发送验证码" forState:UIControlStateNormal];
                
                [resetyanzhengbtn setTitleColor:[UIColor colorWithRed:47/255.0 green:147/255.0 blue:258/255.0 alpha:1] forState:UIControlStateNormal];
                
                resetyanzhengbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [resetyanzhengbtn setTitle:[NSString stringWithFormat:@"%2d秒后重新发送", seconds] forState:UIControlStateNormal];
                [resetyanzhengbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                resetyanzhengbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
    
    
}



- (void)createUIwithPhonestring:(NSString *)phonestring{


    //适配字体大小,圆角大小
    
    float fontsie = 15;
    
    float cornersize = 20;
    
    fontsie = SCREEN_H < 667 ? 13 :  17;
    
    cornersize = SCREEN_H < 667 ? 18 : 22 ;
    
    
    if (SCREEN_H == 667) {
        
        fontsie = 15;
        
        cornersize = 20;
        
    }
    
    self.backgroundColor = [UIColor whiteColor];
    
    UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 20, 80.0/W_BASE*SCREEN_W, 44)];
    
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    UIFont * iconfont = [UIFont fontWithName:@"iconfont" size:fontsie+4];
    
    btn.titleLabel.font = iconfont;
    
    [btn setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [self addSubview:btn];
    
    btn.tag = RETURN_BTN;
    
    [btn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, SCREEN_W, 44)];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.font = [UIFont systemFontOfSize:fontsie+2];
    
    [self addSubview:titlelab];
    
    titlelab.text = @"请输入短信验证码";
    
    UILabel * phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    [self addSubview:phonelabel];
    
    phonelabel.textColor = [UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0 alpha:1];
    
    phonelabel.font = [UIFont systemFontOfSize:fontsie-2];
    
    phonelabel.textAlignment = NSTextAlignmentCenter;
    
    
    NSString * phonehidestr1 = [phonestring substringToIndex:4];
    
    NSString * phonehidestr2 = [phonestring substringFromIndex:7];
    
    // NSLog(@"前缀截取 is %@,后缀截取 is %@",phonehidestr1,phonehidestr2);
    
    phonelabel.text = [NSString stringWithFormat:@"短信验证码已发送至%@****%@,请注意查收",phonehidestr1,phonehidestr2];
    
    
    
    yanzhengtf = [[UITextField alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonelabel.frame)+10.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    yanzhengtf.layer.borderWidth = 1;
    
    yanzhengtf.font = [UIFont systemFontOfSize:fontsie];
    
    //设置tf的缩紧，靠右缩紧，给tf加一个leftview
    
    UIView * leftview  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    yanzhengtf.leftView = leftview;
    
    yanzhengtf.leftViewMode = UITextFieldViewModeAlways;
    
    yanzhengtf.layer.borderColor = [[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1]CGColor];
    
    yanzhengtf.placeholder = @"验证码";
    
    yanzhengtf.clearButtonMode = UITextFieldViewModeAlways;
    
    yanzhengtf.layer.cornerRadius = cornersize;
    
    [self addSubview:yanzhengtf];
    
    yanzhengtf.delegate = self;
    
    yanzhengtf.keyboardType = UIKeyboardTypeNumberPad;

    nextbtn = [[UIButton alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(yanzhengtf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    
    nextbtn.backgroundColor = [UIColor colorWithRed:47.0/255 green:148.0/255 blue:251.0/255 alpha:0.5];
    
    [nextbtn setTitle:@"下一步" forState:UIControlStateNormal];
    
    nextbtn.layer.cornerRadius = cornersize;
    
    nextbtn.titleLabel.font = [UIFont systemFontOfSize:fontsie];
    
    [self addSubview:nextbtn];
    
    nextbtn.tag = NEXT_View;
    
    
    [nextbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    nextbtn.userInteractionEnabled = NO;
    
    
    //重新发送验证码
    
    resetyanzhengbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(nextbtn.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    resetyanzhengbtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [resetyanzhengbtn setTitleColor:[UIColor colorWithRed:47/255.0 green:147/255.0 blue:258/255.0 alpha:1] forState:UIControlStateNormal];
    
    resetyanzhengbtn.titleLabel.font = [UIFont systemFontOfSize:fontsie];
    
    [resetyanzhengbtn  setTitle:@"60秒后重新发送" forState:UIControlStateNormal];
    
    [self addSubview:resetyanzhengbtn];
    
    [resetyanzhengbtn addTarget:self action:@selector(AgainYanzheng) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self loadTimer];






}


#pragma mark ---- TEXTfileld Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    NSString * teststring = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (teststring.length >= 1) {
        
        nextbtn.backgroundColor = [UIColor colorWithRed:47.0/255 green:148.0/255 blue:251.0/255 alpha:1];
        
        nextbtn.userInteractionEnabled = YES;
        
    }

   
//    NSString * teststring = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    
//    if (teststring.length >= 6) {
//        
//        nextbtn.backgroundColor = [UIColor colorWithRed:47.0/255 green:148.0/255 blue:251.0/255 alpha:1];
//        
//        nextbtn.userInteractionEnabled = YES;
//        
//    }
//    
//    
    
    return YES;
    
    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{


    [self endEditing:YES];
    
    return YES;


}


#pragma MARK  ---------- Action ------------

#pragma mark --------------------------重新发送验证码----------------
- (void)AgainYanzheng{
    
    //重新发送验证码
    
    [self.Resetpass2Delegate enterResetPassVC2BtnType:ResetPassView2BtnClickAgainCodeBtn andCodestring:yanzhengtf.text];

    
    [self loadTimer];
    
    
    
}


#pragma mark -------- -- -- - - -调用代理方法 -- - - -- - -- - - --
- (void)enterClick:(UIButton *)btn{



    NSInteger btn_tag = btn.tag;
    
    switch (btn_tag) {
            
        case RETURN_BTN:
            
            
            [self.Resetpass2Delegate enterResetPassVC2BtnType:ResetPassView2BtnClickReturn andCodestring:yanzhengtf.text];
            
            break;
            
            case NEXT_View:
            
            NSLog(@"下一页");
            if (yanzhengtf.text.length != 6) {
                ALERT(@"提示", @"验证码位数不对", self, @"确定", nil);
                return;
            }
            [self.Resetpass2Delegate enterResetPassVC2BtnType:ResetPassView2BtnClickNextBtn andCodestring:yanzhengtf.text];
            
            break;
            
        default:
            
            break;
            
            
            
    }

}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [yanzhengtf resignFirstResponder];
    
    
}

- (void)stopTimer{

    // 页面消失时，终止定时器
    
    //终止定时器
    if (_timer) {
        
        dispatch_source_cancel(_timer);
        
    }
    
    
    //改变view.btn 的字样及颜色
    NSLog(@"消失界面更改");
    
    [resetyanzhengbtn setTitle:@"重新发送验证码" forState:UIControlStateNormal];
    
    resetyanzhengbtn.layer.borderColor = [UIColor colorWithRed:238/255.0 green:240/255.0 blue:239/255.0 alpha:1].CGColor;
    
    

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
